package com.weijun.keepalive.receiver

import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Looper
import com.weijun.keepalive.ACTION_SCREEN_OFF
import com.weijun.keepalive.ACTION_SCREEN_ON
import com.weijun.keepalive.activity.OnePixelActivity
import com.weijun.keepalive.logE

/**
 * @author: weijun
 * date: 2023/7/5
 * description:
 * ①屏幕关闭，播放无声音频，延迟1秒启动一像素 Activity
 * ②屏幕开启，关闭一像素 Activity，停止播放无声音频
 */
class OnePixelReceiver : BroadcastReceiver() {

    private val mHandler by lazy(LazyThreadSafetyMode.NONE) { Handler(Looper.getMainLooper()) }
    private var screenOn = true

    override fun onReceive(context: Context?, intent: Intent?) {
        "OnePixelReceiver onReceive:${intent?.action}".logE()
        when (intent?.action) {
            Intent.ACTION_SCREEN_OFF -> { //屏幕关闭的时候接受到广播
                screenOn = false
                mHandler.postDelayed({
                    if (screenOn) {
                        return@postDelayed
                    }
                    try {
                        PendingIntent.getActivity(
                            context, 0,
                            Intent(context, OnePixelActivity::class.java).apply {
                                addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
                                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                            },
                            PendingIntent.FLAG_IMMUTABLE
                        ).send()
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                },1000)
                context?.sendBroadcast(Intent(ACTION_SCREEN_OFF)) //通知屏幕已关闭，开始播放无声音乐
            }
            Intent.ACTION_SCREEN_ON -> { //屏幕打开的时候发送广播
                screenOn = true
                context?.sendBroadcast(Intent(ACTION_SCREEN_ON)) //通知屏幕已点亮，停止播放无声音乐
            }
            else -> {}
        }
    }
}